#include "env.h"

void Env::push(void) {
	int of=table.empty()?0:table.back().offset;
	table.push_back({of});
}

void Env::put(Id id) {
	id.setOffset(table.back().offset);
	table.back().offset+=id.getType()->getWidth();
	table.back().vars.emplace(id.getName(),id);
}

Id* Env::getTop(std::string name) {
	std::unordered_map<std::string,Id>::iterator p=table.back().vars.find(name);
	if (p!=table.back().vars.end()) {
		return &p->second;
	}
	return nullptr;
}

Id* Env::get(std::string name) {
	for (std::vector<EnvNode>::iterator p=table.begin(); p!=table.end(); ++p) {
		std::unordered_map<std::string,Id>::iterator p1=p->vars.find(name);
		if (p1!=p->vars.end()) {
			return &p1->second;
		}
	}
	return nullptr;
}

void Env::pop(void) {
	table.pop_back();
}

const std::unordered_map<std::string,Id>& Env::getCurNode(void) const {
	return table.back().vars;
}
